from multiprocessing.spawn import old_main_modules
from rest_framework.exceptions import NotAuthenticated, NotFound
from django.db import DatabaseError
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework import status

# 定义自定义异常类
def custom_exception_handler(exc, context):

    # 调用默认的异常处理程序获取响应
    response = exception_handler(exc, context)
    
    # 判断异常是否被drf处理
    if response is None:
        view = context['view']
        # 异常没有被drf处理
        # notAuhendticated
        if isinstance(exc, DatabaseError):
            # 1000 服务器错误
            return Response({'code': 1000, "message":"服务器错误！", 'deatil': str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    else:
        # 异常被drf处理(验证错误，认证错误，资源不存在等)

        if isinstance(exc, NotAuthenticated):
            response.data = {
                'code': 1001,
                'message': '需要身份验证', 
                'detail': "请登录后再访问！"
            }
        elif isinstance(exc, NotFound):
            response.data = {
                "code": 1002,
                'message': '资源不存在',
                'detail': '当前资源不存在，请联系管理员！'
            }

    return response
        
   
